package com.threegroup.admin.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.threegroup.admin.dao.SysRoleDataScopeDao;
import com.threegroup.admin.entity.SysRoleDataScopeEntity;
import com.threegroup.admin.service.ISysRoleDataScopeService;
import com.threegroup.common.constant.Constant;
import com.threegroup.common.utils.RequestHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * 角色数据权限
 *
 */
@Service
public class SysRoleDataScopeServiceImpl implements ISysRoleDataScopeService {

    @Resource
    private SysRoleDataScopeDao sysRoleDataScopeDao;

    @Override
    public List<Long> getDeptIdList(Long roleId) {
        return sysRoleDataScopeDao.getDeptIdList(roleId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveOrUpdate(Long roleId, List<Long> deptIdList) {

        HttpServletRequest request = RequestHolder.getRequest();
        long userId = Long.parseLong(request.getAttribute(Constant.USER_ID).toString());

        //先删除角色数据权限关系
        deleteByRoleIds(new Long[]{roleId});

        //角色没有一个数据权限的情况
        if(CollUtil.isEmpty(deptIdList)){
            return ;
        }

        //保存角色数据权限关系
        for(Long deptId : deptIdList){
            SysRoleDataScopeEntity sysRoleDataScopeEntity = new SysRoleDataScopeEntity();
            sysRoleDataScopeEntity.setDeptId(deptId);
            sysRoleDataScopeEntity.setRoleId(roleId);
            sysRoleDataScopeEntity.setCreator(userId);
            sysRoleDataScopeEntity.setCreateDate(new Date());

            //保存
            sysRoleDataScopeDao.insert(sysRoleDataScopeEntity);
        }
    }

    @Override
    public void deleteByRoleIds(Long[] roleIds) {
        sysRoleDataScopeDao.deleteByRoleIds(roleIds);
    }
}